package algorithm_demo.demo01;

import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * https://leetcode.cn/problems/merge-k-sorted-lists/
 *
 * @author Api
 * @date 2023/2/4 10:13
 */
public class Code22_MergeKSortedLists {

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static class ListNodeComparator implements Comparator<ListNode> {

        @Override
        public int compare(ListNode o1, ListNode o2) {
            return o1.val - o2.val;
        }
    }

    public static ListNode mergeKLists(ListNode[] lists) {
        if(lists == null){
            return null;
        }
        PriorityQueue<ListNode> heap = new PriorityQueue<ListNode>(new ListNodeComparator());
        for(ListNode listNode : lists){
            if(listNode != null){
                heap.add(listNode);
            }
        }
        if(heap.isEmpty()){
            return null;
        }
        // 获取第一个heap的元素，其他节点均循环处理
        ListNode head = heap.poll();
        ListNode pre = head;
        if(pre.next != null){
            heap.add(pre.next);
        }
        // 处理剩余的节点
        while(!heap.isEmpty()){
            ListNode cur = heap.poll();
            // 需要重新赋值（因为pre是头结点的单链表）
            pre.next = cur;
            pre = cur;
            if(cur.next != null){
                heap.add(cur.next);
            }
        }
        return head;
    }
}
